package com.jihu.design.creatation.prototype;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jihu
 * @date 2021/9/14
 */
public class Mybatis {

    //缓存user
    private Map<String,User> userCache = new HashMap<>();

    public User getUser(String username) throws CloneNotSupportedException {
        User user = null;
        if(!userCache.containsKey(username)){
            //从数据库
            user = getUserFromDb(username);
        } else {
            //从缓存中直接拿 脏缓存问题
            //缓存已经拿到，但是不能直接给
            user = userCache.get(username);
            //从这个对象中快速得到一个克隆体
            user = (User)user.clone();
        }

        return user;
    }

    private User getUserFromDb(String username) throws CloneNotSupportedException {
        System.out.println("从数据库查到："+username);
        User user = new User();
        user.setUsername(username);
        user.setAge(18);
        userCache.put(username,(User) user.clone());
        return user;
    }


}
